<?php
        	
namespace Addons\MoreCustomer\Model;
use Home\Model\WeixinModel;
        	
/**
 * MoreCustomer的微信模型
 */
class WeixinAddonModel extends WeixinModel{
	function reply($dataArr, $keywordArr = array()) {
		$config = getAddonConfig ( 'MoreCustomer' ); // 获取后台插件的配置参数
        $access_token = get_access_token ();
        $res = JsonGet('https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=' . $access_token);
        $resarr = json_decode($res, true);
        if(count($resarr['kf_online_list']) > 0){
//            $min = $resarr['kf_online_list'][0]['accepted_case'];
//            $kf_id = '';
//            foreach($resarr['kf_online_list'] as $value){
//                if($value['accepted_case'] <= $min){
//                    $min = $value['accepted_case'];
//                    $kf_id = $value['kf_id'];
//                };
//            }

            $data = array('touser'=>$dataArr['FromUserName'], 'msgtype'=>'text', 'text'=>array('content'=>urlencode('您好，即将为您分配在线客服，请稍后!')));
            $judge_time = $this->judge_time();
            if(!$judge_time){
                $data['text'] = array('content'=>urlencode('您好，客服人员正常工作时段为8:00-11:30、14:00-17:30, 其他时间可能无法及时回复，敬请谅解!'));
            }
            $cres = JsonPost('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token, urldecode(json_encode($data)));
            $customres = json_decode($cres, true);
            if($customres['errmsg'] == 'ok'){
                $this->replyMoreCustomer();
            }
        }
        else{
            $this->replyText('您好，当前没有客服在线噢，请稍后尝试');
        }
//        $this->replyText('openid:' . $dataArr['FromUserName']);
	}

    public function judge_time()
    {
        $start_time1 = mktime(8,0,0,date('m'),date('d'),date('Y'));
        $end_time1 = mktime(11,30,0,date('m'),date('d'),date('Y'));
        $start_time2 = mktime(14,0,0,date('m'),date('d'),date('Y'));
        $end_time2 = mktime(17,30,0,date('m'),date('d'),date('Y'));
        if(time() > $start_time1 && time() < $end_time1){
            return true;
        }
        else if(time() > $start_time2 && time() < $end_time2){
            return true;
        }
        else{
            return false;
        }
    }

	// 关注公众号事件
	public function subscribe() {
		return true;
	}

	// 取消关注公众号事件
	public function unsubscribe() {
		return true;
	}

	// 扫描带参数二维码事件
	public function scan() {
		return true;
	}
	
	// 自定义菜单事件
	public function click() {
		return true;
	}	
}
        	